package com.lovegu.framework.mybatis.dataSource;

import com.zaxxer.hikari.HikariDataSource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 动态数据源初始化
 *
 * @author 大妖怪 9920664@qq.com
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class DynamicDataSourceInit {

    private final TenantDataSourceRepository tenantDataSourceRepository;
    private final DynamicDataSource dynamicDataSource;
    private final HikariDataSource master;
    private ConcurrentHashMap<Object, Object> dataSourceMap = new ConcurrentHashMap<>();

    @Bean
    public void initDataSource() {
        log.info("init dynamic dataSource start....");
        dataSourceMap.put("master", master);
        List<TenantDataSourceDO> tenantDataSourceDoList = tenantDataSourceRepository.list();
        for (TenantDataSourceDO tenantDataSourceDO : tenantDataSourceDoList) {
            log.info(tenantDataSourceDO.toString());
            HikariDataSource dataSource = new HikariDataSource();
            dataSource.setDriverClassName(tenantDataSourceDO.getDriver());
            dataSource.setJdbcUrl(tenantDataSourceDO.getUrl());
            dataSource.setUsername(tenantDataSourceDO.getUserName());
            dataSource.setPassword(tenantDataSourceDO.getPassword());
            dataSource.setDataSourceProperties(master.getDataSourceProperties());
            dataSourceMap.put(tenantDataSourceDO.getTenantId().toString(), dataSource);
        }
        // 设置数据源
        dynamicDataSource.setDataSources(dataSourceMap);
        /**
         * 必须执行此操作，才会重新初始化AbstractRoutingDataSource 中的 resolvedDataSources，也只有这样，动态切换才会起效
         */
        dynamicDataSource.afterPropertiesSet();
        log.info("init dynamic dataSource end....");
    }
}
